package com.hdu.careerplan.controller;

import com.hdu.careerplan.enums.StatusCode;
import com.hdu.careerplan.exception.WrongKeyInJwtException;
import com.hdu.careerplan.pojo.dto.UserBasicInfoDTO;
import com.hdu.careerplan.pojo.dto.UserEducationInfoDTO;
import com.hdu.careerplan.pojo.dto.UserLoginDTO;
import com.hdu.careerplan.pojo.dto.UserRegisterDTO;
import com.hdu.careerplan.pojo.entity.Resume;
import com.hdu.careerplan.pojo.entity.User;
import com.hdu.careerplan.pojo.entity.UserBasicInfo;
import com.hdu.careerplan.pojo.entity.UserEducationInfo;
import com.hdu.careerplan.pojo.vo.Result;
import com.hdu.careerplan.pojo.vo.ResultData;
import com.hdu.careerplan.service.UserService;
import com.hdu.careerplan.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/account/register")
    public ResultData register(@RequestBody UserLoginDTO userLoginDTO, ServletResponse servletResponse) {
        String phone = userLoginDTO.getPhone();
        String password = userLoginDTO.getPassword();
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        log.info("注册,{},{}", phone, password);
        int registerSituation = userService.register(phone, password);
        if (registerSituation == 0) {
            User loginUser = userService.login(phone, password);
            if (loginUser != null) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("userId", loginUser.getUserId());
                claims.put("phone", loginUser.getPhone());
                String jwt = JwtUtil.generateJWT(claims);

                return Result.success(jwt);
            }
            response.setStatus(401);
            return Result.responseWithNonData(StatusCode.LOGIN_FAILED);
        } else {
            response.setStatus(401);
            return Result.responseWithNonData(StatusCode.REGISTER_FAILED);
        }

    }

    @PostMapping("/account/login")
    public ResultData login(@RequestBody UserRegisterDTO userRegisterDTO, ServletResponse servletResponse) {
        String phone = userRegisterDTO.getPhone();
        String password = userRegisterDTO.getPassword();
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        User loginUser = userService.login(phone, password);
        if (loginUser != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", loginUser.getUserId());
            claims.put("phone", loginUser.getPhone());
            String jwt = JwtUtil.generateJWT(claims);

            return Result.success(jwt);
        }
        ((HttpServletResponse) servletResponse).setStatus(401);
        return Result.responseWithNonData(StatusCode.LOGIN_FAILED);
    }

    /**
     * 更新基本信息
     * @param userBasicInfoDTO
     * @param servletRequest
     * @return
     */
    @PostMapping("/profile/basic")
    public ResultData updateBasicInfo(@RequestBody UserBasicInfoDTO userBasicInfoDTO, ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object phone = JwtUtil.getInfoFromJWT(servletRequest, "phone");
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String jwt = request.getHeader("token");
//        Claims claims = JwtUtil.parseJWT(jwt);
//        String phone = (String) claims.get("phone");
        int updateSituation = userService.updateBasicInfo(userBasicInfoDTO, (String) phone);
        if (updateSituation == 0)
            return Result.responseWithNonData(StatusCode.SUCCESS);
        else
            return Result.responseWithNonData(StatusCode.UPDATE_FAILED);
    }

    /**
     * 获取基本信息
     * @param servletRequest
     * @return
     */
    @GetMapping("/profile/basic")
    public ResultData getBasicInfo(ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object phone = JwtUtil.getInfoFromJWT(servletRequest, "phone");
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String jwt = request.getHeader("token");
//        Claims claims = JwtUtil.parseJWT(jwt);
//        String phone = (String) claims.get("phone");
        UserBasicInfo basicInfo = userService.getBasicInfo((String) phone);
        if (basicInfo != null)
            return Result.responseWithData(StatusCode.SUCCESS, basicInfo);
        else
            return Result.responseWithNonData(StatusCode.NO_CONTENT);


    }

    @PostMapping("/profile/education")
    public ResultData updateEducationInfo(@RequestBody UserEducationInfoDTO userEducationInfoDTO, ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object phone = JwtUtil.getInfoFromJWT(servletRequest, "phone");
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String jwt = request.getHeader("token");
//        Claims claims = JwtUtil.parseJWT(jwt);
//        String phone = (String) claims.get("phone");
        int updateSituation = userService.updateEducationInfo(userEducationInfoDTO, (String) phone);
        if (updateSituation == 0)
            return Result.responseWithNonData(StatusCode.SUCCESS);
        else
            return Result.responseWithNonData(StatusCode.UPDATE_FAILED);
    }

    @GetMapping("/profile/education")
    public ResultData getEducationInfo(ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object phone = JwtUtil.getInfoFromJWT(servletRequest, "phone");
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String jwt = request.getHeader("token");
//        Claims claims = JwtUtil.parseJWT(jwt);
//        String phone = (String) claims.get("phone");
        UserEducationInfo userEducationInfo = userService.getEducationInfo((String) phone);
        if (userEducationInfo != null)
            return Result.responseWithData(StatusCode.SUCCESS, userEducationInfo);
        else
            return Result.responseWithNonData(StatusCode.NO_CONTENT);


    }

    @PostMapping("/profile/resume")
    public ResultData uploadResume(@RequestParam("resume")MultipartFile resumeFile, @RequestParam("data") String formData, ServletRequest servletRequest) throws IOException, WrongKeyInJwtException {
        Object usrId = JwtUtil.getInfoFromJWT(servletRequest, "userId");
        Object phone = JwtUtil.getInfoFromJWT(servletRequest, "phone");
        int i = userService.uploadResume(resumeFile, formData, Long.valueOf(usrId.toString()), (String) phone);
        if (i == 0) return Result.responseWithNonData(StatusCode.SUCCESS);
        else return Result.responseWithNonData(StatusCode.UNKNOWN_ERROR);
    }

    @GetMapping("/profile/resume")
    public ResultData getResume(ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object usrId = JwtUtil.getInfoFromJWT(servletRequest, "userId");
        Resume resume = userService.getResume(Long.valueOf(usrId.toString()));
        if (resume == null) return Result.responseWithNonData(StatusCode.NO_CONTENT);
        else return Result.responseWithData(StatusCode.SUCCESS, resume);

    }

    @GetMapping("/profile/resume/attachment")
    public ResultData downloadResume(ServletRequest servletRequest, ServletResponse servletResponse) throws WrongKeyInJwtException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object usrId = JwtUtil.getInfoFromJWT(servletRequest, "userId");
        File file = userService.downloadResume(Long.valueOf(usrId.toString()));
        if (file == null) return Result.responseWithNonData(StatusCode.UNKNOWN_ERROR);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}",e);
            return Result.responseWithNonData(StatusCode.UNKNOWN_ERROR);
        }


        return null;

    }

}
